<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索和添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="clearGetUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="searchGetUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="180px">
          <template slot-scope="scope">
            <el-tooltip
              :open-delay="400"
              effect="dark"
              content="修改"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditUserDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              :open-delay="400"
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUserById(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              :open-delay="400"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户区域 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <!-- 添加用户的表单 -->
      <el-form
        class="add-user-form"
        ref="addUserFormRef"
        :model="addUserForm"
        label-width="80px"
        :rules="addUserFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clearAddForm">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户区域 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 修改用户的表单 -->
      <el-form
        class="edit-user-form"
        ref="editUserFormRef"
        :model="editForm"
        label-width="80px"
        :rules="addUserFormRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色区域 -->
    <el-dialog title="提示" :visible.sync="setRoleDialogVisible" width="40%" @close="closedDiaog">
      <p>当前的用户：{{ this.userInfo.username }}</p>
      <p>当前的角色：{{ this.userInfo.role_name }}</p>
      <p>
        分配新的角色：
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSetRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    let checkEmail = (rule, value, callback) => {
      let reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (!reg.test(value)) {
        return callback(new Error('您输入的邮箱格式不正确'))
      }
      callback()
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      // 添加用户表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度应在3到10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 12,
            message: '长度应在6到12个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            min: 11,
            max: 11,
            message: '您输入的手机号码格式不正确',
            trigger: 'blur'
          }
        ]
      },
      editDialogVisible: false,
      editForm: {},
      setRoleDialogVisible: false,
      userInfo: {},
      roleList: [],
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // removeActivePath() {
    //   window.sessionStorage.clear()
    //   this.$router.push('/home')
    // }
    getUserList() {
      this.$http.get('users', { params: this.queryInfo }).then(
        data => {
          let res = data.data
          if (res.meta.status !== 200) {
            return this.$message.error('获取用户列表失败！')
          }
          this.userList = res.data.users
          this.total = res.data.total
        },
        () => {
          this.$message.error('服务器繁忙！')
        }
      )
    },
    clearGetUserList() {
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    searchGetUserList() {
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(page) {
      this.queryInfo.pagenum = page
      this.getUserList()
    },
    userStateChange(user) {
      this.$http.put(`users/${user.id}/state/${user.mg_state}`).then(
        data => {
          if (data.status !== 200) {
            user.mg_state = !user.mg_state
            return this.$message.error('更新数据失败！')
          }
          this.$message.success('更新数据成功！')
        },
        () => {
          user.mg_state = !user.mg_state
          return this.$message.error('服务器繁忙！')
        }
      )
    },
    clearAddForm() {
      this.dialogVisible = false
      this.$refs.addUserFormRef.resetFields()
    },
    addUser() {
      this.$refs.addUserFormRef.validate(res => {
        if (!res) return this.$message('您输入的格式有误!')
        this.$http.post('users', this.addUserForm).then(
          res => {
            if (res.status === 200) {
              if (res.data.meta.status === 400) {
                return this.$message.error('用户名已存在!')
              } else if (res.data.meta.status === 201) {
                this.dialogVisible = false
                this.$refs.addUserFormRef.resetFields()
                this.getUserList()
                return this.$message.success('添加用户成功!')
              }
            } else {
              this.$message.error('添加用户失败!')
            }
          },
          () => {
            this.$message.error('服务器繁忙!')
          }
        )
      })
    },
    async showEditUserDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('获取用户信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editDialogClosed() {
      this.$refs.editUserFormRef.resetFields()
    },
    editUser() {
      this.$refs.editUserFormRef.validate(validate => {
        if (!validate) return this.$message.error('您输入的格式有误!')
        this.$http
          .put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          .then(res => {
            res = res.data
            if (res.meta.status !== 200) {
              return this.$message.error('修改失败！')
            }
            this.editDialogVisible = false
            this.$message.success('修改成功！')
            this.getUserList()
          })
      })
    },
    deleteUserById(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) return this.$message.error('删除失败！')
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async setRole(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    async confirmSetRole() {
      if (!this.selectedRoleId) {
        return this.message.error('请选择要分配的角色！')
      }
      const { data: res } = await this.$http.put('users/' + this.userInfo.id + '/role', { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败！')
      }
      this.$message.success('分配角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    closedDiaog() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
.add-user-form,
.edit-user-form {
  max-width: 400px;
  margin: 0 auto;
}
</style>
